import os
from xml.dom import minidom
from xml import dom
from xml.dom.minidom import Element

from util.PathUtils import PathUtils

baseWidth: float = 1920
path = PathUtils.getCurrentPath()
parent_path = PathUtils.getParentPath(path)


class Target:
    target_path: str
    dp_width: float

    def __init__(self, target_path, dp_width: float):
        self.target_path = target_path
        self.dp_width = dp_width
        self.scale = dp_width / baseWidth


src_target = Target('values-w1440dp', 640.0)


def dip2Px(dp: float, target: Target):
    return dp / target.scale


def px2dip(px: float, target: Target):
    return px * target.scale


def handleDoc(doc, target: Target):
    newDoc = doc.cloneNode(True)
    es = newDoc.getElementsByTagName("dimen")
    for ele in es:
        handleData(ele, ele.childNodes[0].data, target)
    pass
    target_path = parent_path + "/" + target.target_path + "/dimens.xml"
    p = PathUtils.getParentPath(target_path)
    os.makedirs(p, exist_ok=True)
    # print(target_path)
    file = open(target_path, 'w', encoding='utf8')
    newDoc.writexml(file)


def handleData(element, data: str, target: Target):
    if data.endswith("dp"):
        s = data.replace("dp", "")
        px = dip2Px(int(s), src_target)
        new_dip = px2dip(px, target)
        write_dp = "%ddp" % (round(new_dip))
        # print("old:%s | new:%s" % (data, write_dp))
        element.childNodes[0].data = write_dp
    pass


l = list()

l.append(Target('values-w640dp', 640.0))
l.append(Target('values-w732dp', 732.0))
l.append(Target('values-w975dp', 975.0))
l.append(Target('values-w1440dp', 1440.0))

print(parent_path)
dimens_path = parent_path + "/dimens.xml"

print(dimens_path)

f = open(dimens_path)
d_xml = f.read()

doc = minidom.parseString(d_xml)

for t in l:
    handleDoc(doc, t)
